#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
检查和设置admin用户密码
"""
import os
import sys
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings_ultra_minimal')
django.setup()

from django.contrib.auth.models import User
from django.contrib.auth import authenticate

def check_admin_status():
    """检查admin用户状态"""
    print("🔍 检查admin用户状态...")
    
    try:
        # 查找admin用户
        admin_users = User.objects.filter(username='admin')
        
        if not admin_users.exists():
            print("❌ admin用户不存在！")
            return None
        
        admin_user = admin_users.first()
        
        print("✅ 找到admin用户:")
        print(f"  - ID: {admin_user.id}")
        print(f"  - 用户名: {admin_user.username}")
        print(f"  - 邮箱: {admin_user.email}")
        print(f"  - 是否为超级用户: {admin_user.is_superuser}")
        print(f"  - 是否为员工: {admin_user.is_staff}")
        print(f"  - 是否激活: {admin_user.is_active}")
        print(f"  - 注册时间: {admin_user.date_joined}")
        print(f"  - 最后登录: {admin_user.last_login or '从未登录'}")
        
        return admin_user
        
    except Exception as e:
        print(f"❌ 检查用户时出错: {e}")
        return None

def test_password(username, password):
    """测试密码是否正确"""
    print(f"\n🔐 测试密码: {password}")
    
    try:
        user = authenticate(username=username, password=password)
        if user:
            print("✅ 密码正确！")
            return True
        else:
            print("❌ 密码错误或用户不存在")
            return False
    except Exception as e:
        print(f"❌ 测试密码时出错: {e}")
        return False

def reset_admin_password():
    """重置admin密码"""
    print("\n🔧 重置admin用户密码...")
    
    try:
        # 删除现有admin用户
        User.objects.filter(username='admin').delete()
        print("🗑️ 已删除现有admin用户")
        
        # 创建新的admin用户
        admin_user = User.objects.create_superuser(
            username='admin',
            email='admin@mes.com',
            password='admin123456'
        )
        
        print("✅ 成功创建新的admin用户！")
        print("📋 新用户信息:")
        print(f"  - 用户名: admin")
        print(f"  - 密码: admin123456")
        print(f"  - 邮箱: admin@mes.com")
        print(f"  - 超级用户: True")
        print(f"  - 员工: True")
        print(f"  - 激活: True")
        
        return True
        
    except Exception as e:
        print(f"❌ 重置密码失败: {e}")
        return False

def main():
    """主函数"""
    print("🔐 Admin密码检查和重置工具")
    print("=" * 50)
    
    # 检查admin用户状态
    admin_user = check_admin_status()
    
    if admin_user:
        # 测试常用密码
        passwords_to_test = [
            'admin123456',
            'admin',
            '123456',
            'password',
            'admin123',
            '380155'  # 基于之前看到的用户ID
        ]
        
        print("\n🔍 测试常用密码...")
        password_found = False
        
        for password in passwords_to_test:
            if test_password('admin', password):
                print(f"🎉 找到正确密码: {password}")
                password_found = True
                break
        
        if not password_found:
            print("\n❌ 未找到正确密码")
            reset_choice = input("是否重置admin密码？(y/n): ").lower()
            if reset_choice in ['y', 'yes']:
                reset_admin_password()
            else:
                print("操作已取消")
    else:
        print("\n❌ admin用户不存在")
        create_choice = input("是否创建admin用户？(y/n): ").lower()
        if create_choice in ['y', 'yes']:
            reset_admin_password()
        else:
            print("操作已取消")
    
    print("\n" + "=" * 50)
    print("💡 登录信息:")
    print("  用户名: admin")
    print("  密码: admin123456")
    print("  管理后台: http://127.0.0.1:8000/admin/")
    print("🔄 请刷新浏览器页面后重新登录")

if __name__ == "__main__":
    main() 